package com.jzr.board.service

import android.app.Service
import android.content.Intent
import android.os.Build
import android.os.IBinder
import com.google.gson.Gson
import com.jzr.board.base.BaseEvenBus
import com.jzr.board.bean.CallBean
import com.jzr.board.bean.OxyBean
import com.jzr.board.bean.WebSocketReqBean
import com.jzr.board.bean.WebSocketSendBean
import com.jzr.board.utils.PreferUtil
import com.zhangke.websocket.SimpleListener
import com.zhangke.websocket.SocketListener
import com.zhangke.websocket.WebSocketHandler
import com.zhangke.websocket.response.ErrorResponse
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import java.nio.ByteBuffer

class WebSocketServer : Service() {


    override fun onCreate() {
        super.onCreate()
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        WebSocketHandler.getDefault().addListener(socketListener)
        WebSocketHandler.getDefault().reconnect()

    }

    private val socketListener: SocketListener = object : SimpleListener() {
        override fun onConnected() {
            val sendText = WebSocketSendBean()
         val  d =   PreferUtil.getInstance().websocket
            sendText.deviceNo= PreferUtil.getInstance().websocket
            sendText.cmd = "lgn"
            WebSocketHandler.getDefault().send(Gson().toJson(sendText))
        }

        override fun onConnectFailed(e: Throwable) {
            if (e != null) {

            } else {

            }

        }

        override fun onDisconnect() {

        }

        override fun onSendDataError(errorResponse: ErrorResponse) {
            errorResponse.release()
        }

        override fun <T> onMessage(message: String, data: T) {
            val webReq=  Gson().fromJson(message, WebSocketReqBean::class.java)
            when(webReq.cmd){
                "reload"->{
                    EventBus.getDefault().post(BaseEvenBus(BaseEvenBus.RELOAD))
                }
                "call"->{
                    val callBean=  Gson().fromJson(message, CallBean::class.java)
                    EventBus.getDefault().post(BaseEvenBus(BaseEvenBus.CMD,callBean))
                }
                "oxy"->{
                    val oxyBean=  Gson().fromJson(message, OxyBean::class.java)
                    EventBus.getDefault().post(BaseEvenBus(BaseEvenBus.OXY,oxyBean))
                }

            }
        }

        override fun <T> onMessage(bytes: ByteBuffer, data: T) {

        }

    }

    fun senMessage(text: String?) {
        WebSocketHandler.getDefault().send(text)
    }



    @Subscribe
    fun getEventBus(baseMsg: BaseEvenBus) {

    }

    override fun onDestroy() {
        super.onDestroy()
        WebSocketHandler.getDefault().removeListener(socketListener)
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

}